{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9b88aeb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torchvision import datasets, transforms\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ee7d8a89",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义数据预处理操作，将图像转换为张量并进行归一化\n",
    "transform = transforms.Compose([\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize((0.1307,), (0.3081,))\n",
    "])\n",
    "\n",
    "# 加载训练数据集\n",
    "train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)\n",
    "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)\n",
    "\n",
    "# 加载测试数据集\n",
    "test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n",
    "test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "901e670e",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CNN(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(CNN, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n",
    "        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n",
    "        self.fc1 = nn.Linear(320, 50)\n",
    "        self.fc2 = nn.Linear(50, 10)\n",
    "    def forward(self, x):\n",
    "        x = nn.functional.relu(nn.functional.max_pool2d(self.conv1(x), 2))\n",
    "        x = nn.functional.relu(nn.functional.max_pool2d(self.conv2(x), 2))\n",
    "        x = x.view(-1, 320)\n",
    "        x = nn.functional.relu(self.fc1(x))\n",
    "        x = self.fc2(x)\n",
    "\n",
    "        return x\n",
    "\n",
    "model = CNN()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c525b987",
   "metadata": {},
   "outputs": [],
   "source": [
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ed1f525",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1,   100] loss: 2.031\n",
      "[1,   200] loss: 0.624\n",
      "[1,   300] loss: 0.383\n",
      "[1,   400] loss: 0.294\n",
      "[1,   500] loss: 0.245\n",
      "[1,   600] loss: 0.198\n",
      "[1,   700] loss: 0.182\n",
      "[1,   800] loss: 0.164\n",
      "[1,   900] loss: 0.165\n",
      "[2,   100] loss: 0.138\n",
      "[2,   200] loss: 0.125\n",
      "[2,   300] loss: 0.117\n",
      "[2,   400] loss: 0.105\n",
      "[2,   500] loss: 0.119\n",
      "[2,   600] loss: 0.106\n",
      "[2,   700] loss: 0.096\n",
      "[2,   800] loss: 0.092\n",
      "[2,   900] loss: 0.091\n",
      "[3,   100] loss: 0.082\n",
      "[3,   200] loss: 0.080\n",
      "[3,   300] loss: 0.085\n",
      "[3,   400] loss: 0.089\n",
      "[3,   500] loss: 0.076\n",
      "[3,   600] loss: 0.081\n",
      "[3,   700] loss: 0.066\n",
      "[3,   800] loss: 0.062\n",
      "[3,   900] loss: 0.069\n",
      "[4,   100] loss: 0.071\n",
      "[4,   200] loss: 0.071\n",
      "[4,   300] loss: 0.057\n",
      "[4,   400] loss: 0.060\n",
      "[4,   500] loss: 0.054\n",
      "[4,   600] loss: 0.067\n",
      "[4,   700] loss: 0.055\n",
      "[4,   800] loss: 0.056\n",
      "[4,   900] loss: 0.068\n",
      "[5,   100] loss: 0.061\n",
      "[5,   200] loss: 0.053\n",
      "[5,   300] loss: 0.051\n",
      "[5,   400] loss: 0.057\n",
      "[5,   500] loss: 0.055\n",
      "[5,   600] loss: 0.051\n",
      "[5,   700] loss: 0.055\n",
      "[5,   800] loss: 0.053\n",
      "[5,   900] loss: 0.044\n",
      "[6,   100] loss: 0.044\n",
      "[6,   200] loss: 0.043\n",
      "[6,   300] loss: 0.049\n",
      "[6,   400] loss: 0.049\n",
      "[6,   500] loss: 0.045\n",
      "[6,   600] loss: 0.057\n",
      "[6,   700] loss: 0.047\n",
      "[6,   800] loss: 0.045\n",
      "[6,   900] loss: 0.039\n",
      "[7,   100] loss: 0.040\n",
      "[7,   200] loss: 0.045\n",
      "[7,   300] loss: 0.041\n",
      "[7,   400] loss: 0.038\n",
      "[7,   500] loss: 0.042\n",
      "[7,   600] loss: 0.039\n",
      "[7,   700] loss: 0.043\n",
      "[7,   800] loss: 0.049\n",
      "[7,   900] loss: 0.042\n",
      "[8,   100] loss: 0.038\n",
      "[8,   200] loss: 0.033\n",
      "[8,   300] loss: 0.036\n",
      "[8,   400] loss: 0.032\n",
      "[8,   500] loss: 0.045\n",
      "[8,   600] loss: 0.044\n",
      "[8,   700] loss: 0.038\n",
      "[8,   800] loss: 0.035\n",
      "[8,   900] loss: 0.037\n",
      "[9,   100] loss: 0.032\n",
      "[9,   200] loss: 0.030\n",
      "[9,   300] loss: 0.037\n",
      "[9,   400] loss: 0.040\n",
      "[9,   500] loss: 0.033\n",
      "[9,   600] loss: 0.027\n",
      "[9,   700] loss: 0.036\n",
      "[9,   800] loss: 0.036\n",
      "[9,   900] loss: 0.037\n",
      "[10,   100] loss: 0.032\n",
      "[10,   200] loss: 0.032\n",
      "[10,   300] loss: 0.031\n",
      "[10,   400] loss: 0.031\n",
      "[10,   500] loss: 0.032\n",
      "[10,   600] loss: 0.030\n",
      "[10,   700] loss: 0.034\n",
      "[10,   800] loss: 0.033\n",
      "[10,   900] loss: 0.028\n"
     ]
    }
   ],
   "source": [
    "epochs = 10\n",
    "for epoch in range(epochs):\n",
    "    running_loss = 0.0\n",
    "    for batch_idx, (data, target) in enumerate(train_loader):\n",
    "        optimizer.zero_grad()\n",
    "        output = model(data)\n",
    "        loss = criterion(output, target)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        running_loss += loss.item()\n",
    "        if batch_idx % 100 == 99:\n",
    "            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 100))\n",
    "            running_loss = 0.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3530efe9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy of the network on the 10000 test images: 98 %\n"
     ]
    }
   ],
   "source": [
    "correct = 0\n",
    "total = 0\n",
    "with torch.no_grad():\n",
    "    for data, target in test_loader:\n",
    "        output = model(data)\n",
    "        _, predicted = torch.max(output.data, 1)\n",
    "        total += target.size(0)\n",
    "        correct += (predicted == target).sum().item()\n",
    "\n",
    "print('Accuracy of the network on the 10000 test images: %d %%' % (\n",
    "    100 * correct / total))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "63994e58",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(model.state_dict(),'model.pth')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "DL",
   "language": "python",
   "name": "dl"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
